package com.xunji.xunji.module.account.controller;

import android.support.annotation.Nullable;

import com.huanxiao.base.common.bean.EventMessage;
import com.huanxiao.base.constant.Const;
import com.huanxiao.base.constant.EventConst;
import com.huanxiao.base.constant.SPConst;
import com.huanxiao.base.net.RespResult;
import com.huanxiao.util.SPHelper;
import com.xunji.xunji.module.account.bean.TokenInfo;
import com.xunji.xunji.module.account.bean.UserInfo;
import com.xunji.xunji.module.account.mvp.model.IUserModel;
import com.xunji.xunji.module.account.mvp.model.impl.UserModel;
import com.xunji.xunji.net.ParamManager;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 账户管理
 * Created by paul on 16/10/18.
 */

public class UserAccount {
    private static final String SP_TOKEN = "sp_token";
    private static final String SP_USER_INFO = "sp_user_info";
    private static final String SP_IS_LOGIN = "sp_is_login";
    private boolean isLogin = false;

    private static UserAccount sInstance;

//    public String mToken;

    private IUserModel mUserModel;

    private UserInfo mUserInfo;

    private String mQiniuToken;

    private UserAccount() {
        mUserModel = new UserModel();
    }


    public static UserAccount getInstance() {
        if (sInstance == null) {
            synchronized (UserAccount.class) {
                sInstance = new UserAccount();
            }
        }

        return sInstance;
    }

    public String getQiniuToken() {
        return mQiniuToken;
    }

    public void setQiniuToken(String mQiniuToken) {
        this.mQiniuToken = mQiniuToken;
    }
    //    public String getToken() {
//        return mToken;
//    }

    public void setToken(String token) {
        SPHelper.save(SP_TOKEN, token);
//        mToken = token;
        Const.TOKEN = token;
    }

    public UserInfo getUserInfo() {
        return mUserInfo;
    }

    public String getNickname() {
        if (mUserInfo == null) {
            return "";
        } else {
            return mUserInfo.getNickname();
        }
    }

    public void setUserInfo(UserInfo userInfo) {
        mUserInfo = userInfo;
        SPHelper.saveObject(SP_USER_INFO, userInfo);
    }

    /**
     * 初始化个人信息
     */
    public void init() {

//        this.mToken = SPHelper.get(SP_TOKEN, "");
        Const.TOKEN = SPHelper.get(SP_TOKEN, "");
        this.isLogin = SPHelper.getBoolean(SP_IS_LOGIN, false);

    }

    /**
     * 更新token
     */
    public void refreshToken(@Nullable final Subscriber<RespResult<TokenInfo>> subscribe) {
        mUserModel.tokenCreate(ParamManager.token(new HashMap<String, String>()))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RespResult<TokenInfo>>() {
                    @Override
                    public void onCompleted() {
                        if (subscribe != null) {
                            subscribe.onCompleted();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (subscribe != null) {
                            subscribe.onError(e);
                        }
                    }

                    @Override
                    public void onNext(RespResult<TokenInfo> tokenRespResult) {
                        setToken(tokenRespResult.getData().getToken());
                        if (subscribe != null) {
                            subscribe.onNext(tokenRespResult);
                        }
                    }
                });
    }

    public void refreshQiniuToken() {
        if (!isLogin()) {
            return;
        }
        mUserModel.getQiniuUpToken(ParamManager.onlyTokenParam())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RespResult<String>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(RespResult<String> respResult) {
                        mQiniuToken = respResult.getData();
                    }
                });
    }

    /**
     * 刷新用户信息
     *
     * @param subscriber
     */
    public void refreshUserInfo(final Subscriber<RespResult<UserInfo>> subscriber) {
        if (!isLogin()) {
            return;
        }
        mUserModel.userInfo(ParamManager.getUserInfoParam(SPHelper.get(SPConst.SP_LOGIN_PHONE, "")))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RespResult<UserInfo>>() {
                    @Override
                    public void onCompleted() {
                        if (subscriber != null) {
                            subscriber.onCompleted();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (subscriber != null) {
                            subscriber.onError(e);
                        }
                    }

                    @Override
                    public void onNext(RespResult<UserInfo> result) {
                        setUserInfo(result.getData());
                        if (subscriber != null) {
                            subscriber.onNext(result);
                        }
                    }
                });
    }

    /**
     * 发送验证码
     */
    public void sendSmsCode(String phone, String captcha, final Subscriber<RespResult> subscriber) {
        mUserModel.sendCode(ParamManager.getSmscodeParam(phone))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RespResult>() {
                    @Override
                    public void onCompleted() {
                        if (subscriber != null) {
                            subscriber.onCompleted();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        if (subscriber != null) {
                            subscriber.onError(e);
                        }
                    }

                    @Override
                    public void onNext(RespResult respResult) {
                        if (subscriber != null) {
                            subscriber.onNext(respResult);
                        }
                    }
                });
    }

    public void sendForgetSmsCode(String phone, final Subscriber<RespResult> subscriber) {
        mUserModel.sendForgetCode(ParamManager.getSmscodeParam(phone))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RespResult>() {
                    @Override
                    public void onCompleted() {
                        if (subscriber != null) {
                            subscriber.onCompleted();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        if (subscriber != null) {
                            subscriber.onError(e);
                        }
                    }

                    @Override
                    public void onNext(RespResult respResult) {
                        if (subscriber != null) {
                            subscriber.onNext(respResult);
                        }
                    }
                });
    }

    /**
     * 登录
     *
     * @param phone
     * @param password
     * @param subscriber
     */
    public void login(String phone, String password, String capture, final Subscriber<RespResult<String>> subscriber) {
        mUserModel.userLogin(ParamManager.loginParam(phone, password, capture))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RespResult<String>>() {
                    @Override
                    public void onCompleted() {
                        if (subscriber != null) {
                            subscriber.onCompleted();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (subscriber != null) {
                            subscriber.onError(e);
                        }
                    }

                    @Override
                    public void onNext(RespResult<String> accountInfoRespResult) {
                        isLogin = true;
                        SPHelper.saveBoolean(SP_IS_LOGIN, isLogin);
                        SPHelper.save(SP_TOKEN, accountInfoRespResult.getData());
                        Const.TOKEN = accountInfoRespResult.getData();
//                        mToken = accountInfoRespResult.getData().getToken();
                        EventBus.getDefault().post(new EventMessage(EventConst.EVENT_LOGIN));
                        subscriber.onNext(accountInfoRespResult);
                    }
                });
    }

    public void register(String phone, String verify, String password, final Subscriber<RespResult> subscriber) {
        mUserModel.register(ParamManager.register(phone, verify, password))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RespResult>() {
                    @Override
                    public void onCompleted() {
                        if (subscriber != null)
                            subscriber.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (subscriber != null)
                            subscriber.onError(e);
                    }

                    @Override
                    public void onNext(RespResult respResult) {
                        if (subscriber != null)
                            subscriber.onNext(respResult);
                    }
                });
    }


    public void resetPswd(String phone, String verify, String password, final Subscriber<RespResult> subscriber) {
        mUserModel.resetPswd(ParamManager.register(phone, verify, password))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RespResult>() {
                    @Override
                    public void onCompleted() {
                        if (subscriber != null)
                            subscriber.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (subscriber != null)
                            subscriber.onError(e);
                    }

                    @Override
                    public void onNext(RespResult respResult) {
                        if (subscriber != null)
                            subscriber.onNext(respResult);
                    }
                });
    }

    public void changePswd(String oldPassword, String newPassword, final Subscriber<RespResult> subscriber) {
        mUserModel.changePswd(ParamManager.changePswd(oldPassword, newPassword))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RespResult>() {
                    @Override
                    public void onCompleted() {
                        if (subscriber != null)
                            subscriber.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (subscriber != null)
                            subscriber.onError(e);
                    }

                    @Override
                    public void onNext(RespResult respResult) {
                        if (subscriber != null)
                            subscriber.onNext(respResult);
                    }
                });
    }


    public void thirdLogin(String openId, String from, String appid, final Subscriber<RespResult<TokenInfo>> subscriber) {
        mUserModel.thirdLogin(ParamManager.thirdLogin(appid, openId, from))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RespResult<TokenInfo>>() {
                    @Override
                    public void onCompleted() {
                        if (subscriber != null)
                            subscriber.onCompleted();

                    }

                    @Override
                    public void onError(Throwable e) {

                        if (subscriber != null)
                            subscriber.onError(e);
                    }

                    @Override
                    public void onNext(RespResult<TokenInfo> accountInfoRespResult) {

                        if (subscriber != null)
                            subscriber.onNext(accountInfoRespResult);

                        isLogin = true;
                        SPHelper.saveBoolean(SP_IS_LOGIN, isLogin);
                        SPHelper.save(SP_TOKEN, accountInfoRespResult.getData().getToken());
                        Const.TOKEN = accountInfoRespResult.getData().getToken();
//                        mToken = accountInfoRespResult.getData().getToken();
                        EventBus.getDefault().post(new EventMessage(EventConst.EVENT_LOGIN));
                        subscriber.onNext(accountInfoRespResult);
                    }
                });
    }

    /**
     * 退出登录
     */
    public void loginOutRequest(final Subscriber<RespResult> subscriber) {
        mUserModel.loginOut(ParamManager.onlyTokenParam())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RespResult>() {
                    @Override
                    public void onCompleted() {
                        if (subscriber != null) {
                            subscriber.onCompleted();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        if (subscriber != null) {
                            subscriber.onError(e);
                        }
                    }

                    @Override
                    public void onNext(RespResult respResult) {
                        if (subscriber != null) {
                            subscriber.onNext(respResult);
                        }
                        logout();
                        EventBus.getDefault().post(new EventMessage(EventConst.EVENT_LOGOUT));

                    }
                });
    }


    /**
     * 退出
     */
    public void logout() {
        isLogin = false;
        SPHelper.remove(SP_IS_LOGIN);
        SPHelper.remove(SP_USER_INFO);
        mUserInfo = null;
        Const.TOKEN = "";
    }


    public void setLogin(boolean login) {
        isLogin = login;
    }

    /**
     * 判断是否登录
     *
     * @return
     */
    public boolean isLogin() {
        return isLogin;
    }
}
